package com.buaa.aimall.userModule.Controller;

import com.buaa.aimall.Utils.Config.JeepayConfig;
import com.buaa.aimall.Utils.PageReturnResult;
import com.buaa.aimall.userModule.DTO.FilterWithdrawalWorkOrderDTO;
import com.buaa.aimall.userModule.DTO.PageDTO;
import com.buaa.aimall.userModule.DTO.ProcessWithdrawalDTO;
import com.buaa.aimall.userModule.DTO.WithdrawalDTO;
import com.buaa.aimall.userModule.Entity.UserEntity;
import com.buaa.aimall.userModule.Entity.WithdrawalWorkOrderEntity;
import com.buaa.aimall.Utils.Enum.StatusCode;
import com.buaa.aimall.Utils.Enum.WorkOrderStatusEnum;
import com.buaa.aimall.userModule.Enum.PayOrderStatusEnum;
import com.buaa.aimall.userModule.Service.JeepayService;
import com.buaa.aimall.userModule.Service.UserService;
import com.buaa.aimall.userModule.Service.WithdrawalWorkOrderService;
import com.buaa.aimall.Utils.BaseResponse;
import com.buaa.aimall.Utils.MinioUtils;
import com.jeequan.jeepay.response.TransferOrderCreateResponse;
import io.minio.messages.Item;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@CrossOrigin
public class WithdrawalController {

    @Autowired
    private UserService userService;

    @Autowired
    private WithdrawalWorkOrderService withdrawalWorkOrderService;

    @Autowired
    private JeepayService jeepayService;

    @Autowired
    private MinioUtils minioUtils;

    private final JeepayConfig jeepayConfig;

    @Autowired
    public WithdrawalController(JeepayConfig jeepayConfig) {
        this.jeepayConfig = jeepayConfig;
    }

    @PostMapping("/withdrawal")
    public BaseResponse<Boolean> withdrawal(@RequestBody WithdrawalDTO withdrawalDTO) {
        UserEntity user = userService.getCurrentUser();
        if (withdrawalDTO.getAmount() <= 0) {
            return new BaseResponse<>(StatusCode.PARAM_ERROR, "非法金额", Boolean.FALSE);
        }
        if (withdrawalDTO.getAmount() > user.getIncome()) {
            return new BaseResponse<>(StatusCode.INSUFFICIENT_BALANCE, "收益余额不足", Boolean.FALSE);
        }
        WithdrawalWorkOrderEntity withdrawalWorkOrderEntity = WithdrawalWorkOrderEntity.builder()
                .amount(withdrawalDTO.getAmount())
                .creator(user.getId())
                .status(WorkOrderStatusEnum.PROCESSING)
                .accountNo(withdrawalDTO.getAccountNo())
                .accountName(withdrawalDTO.getAccountName())
                .build();
        withdrawalWorkOrderService.save(withdrawalWorkOrderEntity);
        return new BaseResponse<>(StatusCode.SUCCESS, "提现收益申请成功", Boolean.TRUE);
    }

    @PostMapping("/process-withdrawal")
    public BaseResponse<TransferOrderCreateResponse> processWithdrawal(@Valid @RequestBody ProcessWithdrawalDTO processWithdrawalDTO) {
        UserEntity processor = userService.getCurrentUser();
        WithdrawalWorkOrderEntity withdrawalWorkOrderEntity = withdrawalWorkOrderService.getById(processWithdrawalDTO.getId());

        if (withdrawalWorkOrderEntity == null) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, "收益提现工单不存在", null);
        }
        if (withdrawalWorkOrderEntity.getStatus() != WorkOrderStatusEnum.PROCESSING) {
            return new BaseResponse<>(StatusCode.WITHDRAWAL_WORK_ORDER_PROCESSED, "收益提现工单已处理，不可再次审核处理", null);
        }
        if (processWithdrawalDTO.getStatus() == WorkOrderStatusEnum.PROCESSING) {
            return new BaseResponse<>(StatusCode.PARAM_ERROR, "请求status不可为PROCESSING", null);
        }

        if (processWithdrawalDTO.getStatus() == WorkOrderStatusEnum.APPROVED) {
            TransferOrderCreateResponse response = jeepayService.withdrawalTransfer(
                    withdrawalWorkOrderEntity.getAmount(),
                    userService.getById(withdrawalWorkOrderEntity.getCreator()),
                    withdrawalWorkOrderEntity.getAccountNo(),
                    withdrawalWorkOrderEntity.getAccountName());

            if (response == null) {
                return new BaseResponse<>(StatusCode.DAO_ERROR, "向支付网关请求失败", null);
            }
            if (!response.checkSign(jeepayConfig.getApiKey())) {
                return new BaseResponse<>(StatusCode.CHECK_SIGN_FAILED, "支付网关响应验签失败", response);
            }
            if (!response.isSuccess(jeepayConfig.getApiKey())) {
                return new BaseResponse<>(StatusCode.PAY_FAILED, "支付网关创建订单失败", response);
            }

            withdrawalWorkOrderEntity.setStatus(processWithdrawalDTO.getStatus());
            withdrawalWorkOrderEntity.setProcessor(processor.getId()); // todo 审核员权限校验
            withdrawalWorkOrderEntity.setProcessTime(LocalDateTime.now());
            withdrawalWorkOrderEntity.setMchOrderNo(response.getData().getString("mchOrderNo"));
            withdrawalWorkOrderEntity.setMchOrderStatus(PayOrderStatusEnum.PAYMENT_IN_PROGRESS);
            withdrawalWorkOrderService.updateById(withdrawalWorkOrderEntity);
            return new BaseResponse<>(StatusCode.SUCCESS, "收益提现工单状态更改为通过，已发起转账", response);
        }

        return new BaseResponse<>(StatusCode.SUCCESS, "收益提现工单状态更改为拒绝", null);
    }

    @PostMapping("/filter-withdrawal-workorder")
    public BaseResponse<PageReturnResult<WithdrawalWorkOrderEntity>> filterWithdrawalWorkOrder(@RequestBody FilterWithdrawalWorkOrderDTO filterWithdrawalWorkOrderDTO) {
        // todo 审核员鉴权
        PageReturnResult<WithdrawalWorkOrderEntity> result = withdrawalWorkOrderService.filterWithdrawalWorkOrder(filterWithdrawalWorkOrderDTO);
        return new BaseResponse<>(StatusCode.SUCCESS, "批量筛选获取提现工单成功", result);
    }

    @GetMapping("/list-minio-files")
    public BaseResponse<List<Map<String, Object>>> listFiles(@RequestParam(required = false) String prefix) {
        try {
            List<Item> items = minioUtils.listObjects(prefix != null ? prefix : "");
            List<Map<String, Object>> result = new ArrayList<>();

            for (Item item : items) {
                Map<String, Object> fileInfo = new HashMap<>();
                fileInfo.put("fileName", item.objectName());
                fileInfo.put("size", item.size());
                fileInfo.put("lastModified", item.lastModified());
                fileInfo.put("isDirectory", item.isDir());
                result.add(fileInfo);
            }

            return new BaseResponse<>(StatusCode.SUCCESS, "获取文件列表成功", result);
        } catch (Exception e) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, "获取文件列表失败: " + e.getMessage(), null);
        }
    }
}
